package cn.mothin.frame.help;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import cn.mothin.frame.core.interfaces.ISqlHelper;
import cn.mothin.frame.core.interfaces.system.ILoginLogHelper;

@SuppressWarnings("rawtypes")
@Component("527a386b21cd43d7ea6234c6")
public class LoginLogHelper implements ILoginLogHelper, ApplicationListener {
	protected final Log log = LogFactory.getLog(getClass());
	@Autowired
	private ISqlHelper sqlHelper;

	/**
	 * 记录登录系统时间，以及返回会话Id
	 * 
	 * @param id
	 * @param userId
	 * @param ip
	 * @return
	 */
	public String recordLogin(String userId, String ip) {
		String sessionId = UniqueCode.make();
		String sql = "INSERT INTO login_log(id,loginAccountId,loginIp,loginTime) VALUES(?,?,?,?)";
		sqlHelper.execute(sql, sessionId, userId, ip,
				new Date(System.currentTimeMillis()));
		return sessionId;
	}

	public void recordLogin(String id, String userId, String ip) {
		String sql = "INSERT INTO login_log(id,loginAccountId,loginIp,loginTime) VALUES(?,?,?,?)";
		sqlHelper.execute(sql, id, userId, ip,
				new Date(System.currentTimeMillis()));
	}

	/**
	 * 记录退出时间以及退出方式
	 * 
	 * @param id
	 *            会话Id
	 * @param type
	 *            退出方式，只允许正常退出（0）以及超时退出（1）方式。
	 */
	public void recordLogout(String id, int type) {
		if (type == LOGOUT_TYPE_NORMAL || type == LOGOUT_TYPE_OVERTIME) {
			String sql = "UPDATE login_log SET logoutTime=?,logoutType=? WHERE id = ?  AND logoutTime IS NULL ";
			sqlHelper.execute(sql, new Date(System.currentTimeMillis()), type,
					id);
		}
	}

	/**
	 * 服务器启动重置之前未记录退出的记录
	 */
	public void doReset() {
		String sql = "UPDATE login_log SET logoutTime=?,logoutType=? WHERE logoutTime IS NULL";
		try{
			sqlHelper.execute(sql, new Date(System.currentTimeMillis()),LOGOUT_TYPE_RESET);
		}catch(Throwable t){
			log.error(t);
		}
	}

	@Override
	public void onApplicationEvent(ApplicationEvent arg0) {
		doReset();
	}
}
